package com.ignou.mca.login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ignou.mca.beans.Message;
import com.ignou.mca.beans.UserVO;
import com.ignou.mca.datasource.DatabaseOperations;

/**
 * Servlet implementation class VerifyLogin
 */
public class VerifyLogin extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VerifyLogin() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		ServletContext context = getServletContext();
		HttpSession session = null;
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		Message message = new Message();
		
		if(userName.length()<1)
		{
			context.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		}
		else if(password.length()<1)
		{
			context.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		}
		else
		{
			DatabaseOperations dbOperations = new DatabaseOperations();
			UserVO uVO = new UserVO();
			uVO = dbOperations.doLogin(userName, password);
			
			if(uVO!=null && userName.equalsIgnoreCase(uVO.getUserName()) && password.equals(uVO.getPassword()))
			{
				dbOperations.updateLastLogin(userName);
				session = request.getSession();
				session.setAttribute("UserVO", uVO);
				context.getRequestDispatcher("/Home.jsp").forward(request, response);
			}
			else
			{
				request.setAttribute("ErrorMessage", "Invalid user name or password");
				context.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
			}
		}
		
	}
}
